'user strict'
var socket;
var localVideo = document.querySelector("video#localVideo")
var hdButton = document.querySelector("img#hd")
var localStream;
var hd = false;
function handlerError(err) {
    console.log(err.name + ":" + err.message);
}
function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
async function initPeerConnection(name, upload) {
    var pc = new RTCPeerConnection(configuration);
    if (!localStream) {
        localStream = await navigator.mediaDevices.getUserMedia({
            video: { width: 1600, height: 900 },
            audio: {
                echoCancellation: true,
                noiseSuppression: true
            }
        });
        localVideo.srcObject = localStream;
        console.log("get local media:")
        console.log(localStream)
    }

    for (const track of localStream.getTracks()) {
        pc.addTrack(track, localStream);
    }
    pc.onicecandidate = (e) => {
        if (e.candidate) {
            sendCandidate(name, e.candidate)
            console.log("you have send candidate " + name)
            console.log(e.candidate)
        }
    }
    pc.ontrack = (e) => {
        localVideo.srcObject = e.streams[0];
        console.log("get remote stream " + name)
        console.log(e.streams[0])
        
    }
    return pc;
}
function connect() {
    // 判断当前浏览器是否支持webSocket
    if (window.WebSocket) {
        socket = new WebSocket(wsUrl);
        // 相当于channel的read事件，ev 收到服务器回送的消息
        socket.onmessage = function (ev) {
            if (ev.data) {
                var data = ev.data;
                if (ev.data == "Connected") {
                    console.log("登陆成功");
                    watchLive();
                    keepalive();
                    return;
                }
                data = JSON.parse(data);
                const response = JSON.stringify(data);
                console.log(response)
                if (data.jsep) {
                    var jsep = data.jsep;
                    if (jsep.type == "offer") {
                        var plugindata = data.plugindata;
                        var data = plugindata.data;
                        initPeerConnection(id, false).then(function (res) {
                            var pc = res;
                            pc.setRemoteDescription(new RTCSessionDescription(jsep))
                            var answerOptions = {
                                iceRestart: true,
                                answerToReceiveAudio: true,
                                answerToReceiveVideo: true,
                            }
                            pc.createAnswer(answerOptions).then(function (offer) {
                                console.log("you createAnswer:")
                                console.log(offer)
                                return pc.setLocalDescription(offer);
                            }).then(function () {
                                start(pc.localDescription, id)
                                console.log("you have received offer from " + id)
                            }).catch(handlerError);
                        });
                        return;
                    }
                }
                if (data.janus == "event") {
                    data = data.plugindata;
                    data = data.data;
                    if (data.videoroom == "joined") {
                        initLocalWebRtc();
                    }
                    if (data.started == "ok") {
                        substream(id, 0);
                    }
                }
            }
        }
        // 相当于连接开启
        socket.onopen = function (ev) {
            if(!id){
                id = uuid2(16, 16)
            }
            login()
        }
        // 相当于连接关闭
        socket.onclose = function (ev) {
            logout()
        }
    } else {
        alert("当前浏览器不支持webSocket")
    }
}
function prom() {
    room = getQueryVariable("room")
    if (room) {
        connect();
    } else {
        room = Math.floor(Math.random() * (360000) + 1000)
        window.location.href = "?room=" + room
    }
}
function changeHD(){
    if(hd){
        hdButton.src = "../icon/hd-off.svg";
        substream(id,0)
    }else{
        hdButton.src = "../icon/hd-on.svg";
        substream(id,2)
    }
    hd = !hd;
}
prom();
hdButton.onclick = changeHD
// environment.onclick = changeEnvironmentCamera